Main site

Built-in Modules > enrichItemDetails Function

enrichItemDetails Function

Overview

The enrichItemDetails function is an asynchronous utility designed to augment the items field within the input DATA JSON object with additional information, aiding in the comprehensive calculation of shipping rates.

Function Signature

async function enrichItemDetails(DATA, metafield_namespaces = [])

Arguments

  • DATA (Object): The initial DATA JSON object provided to the calculateShippingRates function.
  • metafield_namespaces (Array, Optional): An array specifying metafield namespaces and the quantity of metafields to fetch.
    • Each object within the array contains:
      • namespace (String): The metafield namespace.
      • size (Number): The count of metafield objects to retrieve from the namespace.

Notes

  • Ensure that each entry in metafield_namespaces includes both a namespace and a size.
  • If size is not specified, the default value is 10.

Usage Example

import { enrichItemDetails } from "./modules.js"
DATA = await enrichItemDetails(DATA, [
  { namespace: "shipping", size: 15 },
  { namespace: "carton", size: 15 }
]);

This enriches items object of DATA with more fields including the first 15 metafield objects from the "shipping" namespace and the "carton" namespace. In the sample output below, the fields starting from id are added by the function.

Sample Output

{
  "name": "string",
  "sku": "string",
  "quantity": "number",
  "grams": "number",
  "price": "number",
  "vendor": "string",
  "requires_shipping": "boolean",
  "taxable": "boolean",
  "fulfillment_service": "string",
  "properties": "object",
  "product_id": "number",
  "variant_id": "number",
  "id": "string",
  "itemPrice": "string",
  "compareAtPrice": "string",
  "barcode": "null",
  "weightUnit": "string",
  "weight": "number",
  "variantTitle": "string",
  "displayName": "string",
  "sellingPlanGroupCount": "number",
  "sellableOnlineQuantity": "number",
  "position": "number",
  "inventoryQuantity": "number",
  "inventoryPolicy": "string",
  "deliveryProfile": {
    "id": "string",
    "name": "string",
    "default": "boolean",
    "activeMethodDefinitionsCount": "number"
  },
  "product": {
    "title": "string",
    "productType": "string",
    "productCategory": {
      "productTaxonomyNode": {
        "name": "string"
      }
    },
    "tags": "array",
    "handle": "string",
    "status": "string",
    "collections": {
      "list": "array"
    }
  },
  "selectedOptions": "array",
  "contextualPricing": {
    "price": {
      "amount": "string",
      "currencyCode": "string"
    },
    "compareAtPrice": {
      "amount": "string",
      "currencyCode": "string"
    }
  },
  "metafields": {
    "shipping": {
      "length": "string",
      "weight": "string"
    },
    "carton": {
      "bulky": "string",
      "fragile": "string"
    }
  }
}

Notes

  • The output above includes sample shipping and carton metafield objects.
  • The actual metafields object can contain various other objects as per the specified namespaces.

Sample AI Prompt

I'd like a shipping rate calculator that uses the items total weight, the items total cubic weight and items total price as parameters.
The calculator compares the items total weight in kg to the items total cubic weight. The calculator takes the larger of the two and multiply it by 0.2 cents to calculate the total shipping cost.
If the total items price is more than $500, the calculator provides 10% discount from the total shipping cost.The total items price is the sum of each item price.
The dimension and weight of the each item is contained in the item's metafield namespace object called "shipping". Get the first 15 values in the namespace.
The dimensions are given in cm and the weight is given kilograms.
The delivery date is between 5 to 8 days from now.
Use the cubic conversion rate of 250kg per cubic meter. Make sure to convert units correctly, for example, centimeter to meter.

Sample AI Output

import { enrichItemDetails } from "./modules.js";

export async function calculateShippingRates(DATA, env) {
  try {
    // Enrich items with additional details
    DATA = await enrichItemDetails(DATA, [{ namespace: "shipping", size: 15 }]);

    // Calculate total weight and cubic weight
    let totalWeight = 0;
    let totalCubicWeight = 0;
    for (const item of DATA.items) {
      const shippingMetafield = item.metafields.shipping;
      if (shippingMetafield) {
        const length = parseFloat(shippingMetafield.length) / 100; // Convert cm to m
        const width = parseFloat(shippingMetafield.width) / 100; // Convert cm to m
        const height = parseFloat(shippingMetafield.height) / 100; // Convert cm to m
        const weight = parseFloat(shippingMetafield.weight);

        totalWeight += weight;
        totalCubicWeight += length * width * height * 250; // Convert kg to m^3
      }
    }

    // Calculate total price
    let totalPrice = 0;
    for (const item of DATA.items) {
      totalPrice += item.price;
    }

    // Calculate shipping cost
    let shippingCost = Math.max(totalWeight, totalCubicWeight) * 0.2;

    // Apply discount if total price is more than $500
    if (totalPrice > 50000) {
      shippingCost *= 0.9;
    }

    // Format shipping rates
    const rates = [
      {
        service_name: "Standard Shipping",
        service_code: "standard",
        total_price: shippingCost.toFixed(2),
        description: "Standard shipping",
        currency: DATA.currency,
        min_delivery_date: new Date(Date.now() + 5 * 24 * 60 * 60 * 1000).toISOString(),
        max_delivery_date: new Date(Date.now() + 8 * 24 * 60 * 60 * 1000).toISOString(),
      },
    ];

    return { rates };
  } catch (error) {
    // Return error rate
    return {
      rates: [
        {
          service_name: "",
          service_code: "",
          total_price: null,
          description: "",
          currency: "",
          min_delivery_date: "",
          max_delivery_date: "",
        },
      ],
    };
  }
}